<template>
  <div id="assessdetail">
    <el-form :model="editForm" label-width="300px" ref="editForm" :inline="true" style="padding:10px 0 0;clear:both" v-show="!pageLoading">
      <table cellspacing="0" cellpadding="0" class="mytable">
        <tr><th style="text-align:center;width:40px">编号</th><th colspan="3" style="text-align:center">填报项</th><th style="text-align:center">填写说明</th></tr>
        <template v-for="(item,index) in formData">
          <template v-if="item.children">
            <template v-for="(item1,index1) in item.children">
              <tr :key="index*100+index1">
                <th style="text-align:center;width:40px">{{index+1}}-{{index1+1}}</th>
                <th style="min-width:200px;" v-if="index1===0" :rowspan="item.children.length">{{item.label}}</th>
                <th style="min-width:200px;" v-if="readOnly" >{{item1.label}}</th>
                <td style="min-width:700px;" :colspan="readOnly?1:2">
                  <template v-if="readOnly" >
                    <template v-if="item1.type==='upload'">
                      <template v-if="editForm[item1.title]&&editForm[item1.title].length>0">
                        <a v-for="(it,idx) in editForm[item1.title]" :key="idx" :href="$http.defaults.baseURL + $http.defaults.unitReportAPI + 'api/file/download?id=' + it.id">{{it.name}}<br></a>
                      </template>
                      <template v-else>无</template>
                    </template>
                    <template v-else-if="item1.type==='checkbox'">
                      {{editForm[item1.title].join("、")}}
                    </template>
                    <template v-else>{{editForm[item1.title]}}</template>
                  </template>
                  <template v-else>
                    <el-form-item :prop="item1.title" :label="item1.label" :rules="item1.rules">
                      <el-input
                        v-model="editForm[item1.title]"
                        v-if="item1.type==='string'"
                        style="width:400px;"
                        :maxlength="item1.config?item1.config.maxlength:false"
                        :minlength="item1.config?item1.config.minlength:false"
                        :show-word-limit="true"
                      ></el-input>
                      <el-input
                        v-model="editForm[item1.title]"
                        v-else-if="item1.type==='textarea'"
                        style="width:600px;"
                        type="textarea"
                        :rows="item1.config?item1.config.rows:5"
                        :maxlength="item1.config?item1.config.maxlength:false"
                        :minlength="item1.config?item1.config.minlength:false"
                        :show-word-limit="true"
                      >
                      </el-input>
                      <el-input-number
                        v-model="editForm[item1.title]"
                        v-else-if="item1.type==='number'"
                        :precision="item1.config?item1.config.precision:0"
                        :step="item1.config?item1.config.step:1"
                        :min="item1.config?item1.config.min:null"
                        :max="item1.config?item1.config.max:null"
                      >
                      </el-input-number>
                      <el-date-picker
                        v-model="editForm[item1.title]"
                        v-else-if="item1.type==='date'"
                        :type="item1.dateType?item1.dateType:'date'"
                        :value-format="item1.format?item1.format:'yyyy-MM-dd'"
                        placeholder="选择日期"
                      >
                      </el-date-picker>
                      <el-radio-group
                        v-model="editForm[item1.title]"
                        v-else-if="item1.type==='radio'"
                      >
                        <template v-for="(it,idx) in item1.options">
                          <template v-if="item1.limitNum&&item1.labelText&&item1.limitNum">
                            <el-radio :key="idx" :label="it" :disabled="item1.limitNum[idx]<=item1.inputNum[idx]">{{item1.labelText[idx]}}</el-radio>
                          </template>
                          <template v-else>
                            <el-radio :key="idx" :label="it"></el-radio>
                          </template>
                        </template>
                      </el-radio-group>
                      <el-checkbox-group
                        v-model="editForm[item1.title]"
                        v-else-if="item1.type==='checkbox'"
                      >
                        <el-checkbox v-for="(it,idx) in item1.options" :key="idx" :label="it"></el-checkbox>
                      </el-checkbox-group>
                      <el-select
                        v-model="editForm[item1.title]"
                        v-else-if="item1.type==='select'"
                        placeholder="请选择"
                      >
                        <template v-for="(it,idx) in item1.options">
                          <template v-if="item1.limitNum&&item1.labelText&&item1.limitNum">
                            <el-option :key="idx" :label="item1.labelText[idx]" :value="it" :disabled="item1.limitNum[idx]<=item1.inputNum[idx]" />
                          </template>
                          <template v-else>
                            <el-option :key="idx" :label="it" :value="it" />
                          </template>
                        </template>
                      </el-select>
                      <el-upload
                        v-model="editForm[item1.title]"
                        v-else-if="item1.type==='upload'"
                        :action="$http.defaults.baseURL+$http.defaults.unitReportAPI +'api/file/upload/'"
                        :on-preview="handlePreview"
                        :on-remove="(file, fileList)=>{return handleRemove(file, fileList, item1.title)}"
                        :on-success="(response, file, fileList)=>{return handleUploadSucc(response, file, fileList, item1.title)}"
                        :on-error="uploadError"
                        :before-remove="beforeRemove"
                        :before-upload="beforeUpload"
                        :multiple="false"
                        :on-exceed="handleExceed"
                        :limit="item1.config?item1.config.limit:null"
                        :file-list="editForm[item1.title]">
                        <el-button size="small" type="primary">点击上传</el-button>
                      </el-upload>
                    </el-form-item>
                  </template>
                </td>
                <td style="min-width:400px;">{{item1.remarks}}</td></tr>
            </template>
          </template>
          <template v-else>
            <tr :key="index*100">
              <th style="text-align:center;width:40px">{{index+1}}</th>
              <th style="min-width:200px;" v-if="readOnly" colspan="2" >{{item.label}}</th>
              <td style="min-width:700px;" :colspan="readOnly?1:3">
                <template v-if="readOnly" >
                  <template v-if="item.type==='upload'">
                    <template v-if="editForm[item.title]&&editForm[item.title].length>0">
                      <a v-for="(it,idx) in editForm[item.title]" :key="idx" :href="$http.defaults.baseURL + $http.defaults.unitReportAPI + 'api/file/download?id=' + it.id">{{it.name}}<br></a>
                    </template>
                    <template v-else>无</template>
                  </template>
                  <template v-else-if="item.type==='checkbox'">
                    {{editForm[item.title].join("、")}}
                  </template>
                  <template v-else>{{editForm[item.title]}}</template>
                </template>
                <template v-else>
                  <el-form-item :prop="item.title" :label="item.label" :rules="item.rules" label-width="521px">
                    <el-input
                      v-model="editForm[item.title]"
                      v-if="item.type==='string'"
                      style="width:400px;"
                      :maxlength="item.config?item.config.maxlength:false"
                      :minlength="item.config?item.config.minlength:false"
                      :show-word-limit="true"
                    ></el-input>
                    <el-input
                      v-model="editForm[item.title]"
                      v-else-if="item.type==='textarea'"
                      style="width:600px;"
                      type="textarea"
                      :rows="item.config?item.config.rows:5"
                      :maxlength="item.config?item.config.maxlength:false"
                      :minlength="item.config?item.config.minlength:false"
                      :show-word-limit="true"
                    >
                    </el-input>
                    <el-input-number
                      v-model="editForm[item.title]"
                      v-else-if="item.type==='number'"
                      :precision="item.config?item.config.precision:0"
                      :step="item.config?item.config.step:1"
                      :min="item.config?item.config.min:null"
                      :max="item.config?item.config.max:null"
                    >
                    </el-input-number>
                    <el-date-picker
                      v-model="editForm[item.title]"
                      v-else-if="item.type==='date'"
                      :type="item.dateType?item.dateType:'date'"
                      :value-format="item.format?item.format:'yyyy-MM-dd'"
                      placeholder="选择日期"
                    >
                    </el-date-picker>
                    <el-radio-group
                      v-model="editForm[item.title]"
                      v-else-if="item.type==='radio'"
                    >
                      <template v-for="(it,idx) in item.options">
                        <template v-if="item.limitNum&&item.labelText&&item.limitNum">
                          <el-radio :key="idx" :label="it" :disabled="item.limitNum[idx]<=item.inputNum[idx]">{{item.labelText[idx]}}</el-radio>
                        </template>
                        <template v-else>
                          <el-radio :key="idx" :label="it"></el-radio>
                        </template>
                      </template>
                    </el-radio-group>
                    <el-checkbox-group
                      v-model="editForm[item.title]"
                      v-else-if="item.type==='checkbox'"
                    >
                      <el-checkbox v-for="(it,idx) in item.options" :key="idx" :label="it"></el-checkbox>
                    </el-checkbox-group>
                    <el-select
                      v-model="editForm[item.title]"
                      v-else-if="item.type==='select'"
                      placeholder="请选择"
                    >
                      <template v-for="(it,idx) in item.options">
                        <template v-if="item.limitNum&&item.labelText&&item.limitNum">
                          <el-option :key="idx" :label="item.labelText[idx]" :value="it" :disabled="item.limitNum[idx]<=item.inputNum[idx]" />
                        </template>
                        <template v-else>
                          <el-option :key="idx" :label="it" :value="it" />
                        </template>
                      </template>

                    </el-select>
                    <el-upload
                      v-model="editForm[item.title]"
                      v-else-if="item.type==='upload'"
                      :action="$http.defaults.baseURL+$http.defaults.unitReportAPI +'api/file/upload/'"
                      :on-preview="handlePreview"
                      :on-remove="(file, fileList)=>{return handleRemove(file, fileList, item.title)}"
                      :on-success="(response, file, fileList)=>{return handleUploadSucc(response, file, fileList, item.title)}"
                      :on-error="uploadError"
                      :before-remove="beforeRemove"
                      :before-upload="beforeUpload"
                      :multiple="false"
                      :on-exceed="handleExceed"
                      :limit="item.config?item.config.limit:null"
                      :file-list="editForm[item.title]">
                      <el-button size="small" type="primary">点击上传</el-button>
                    </el-upload>
                  </el-form-item>
                </template>
              </td>
              <td style="min-width:400px;">{{item.remarks}}</td>
            </tr>
          </template>
        </template>
      </table>
      <!-- <table cellspacing="0" cellpadding="0" class="mytable" v-if="readOnly" >
        <tr v-for="(item,index) in formData" :key="index">
          <template v-if="item.children">
            <th style="min-width:200px;">{{item.label}}</th>
            <td style="min-width:700px">
            </td>
            <td style="min-width:300px">{{item.remarks}}
            </td>
          </template>
          <template v-else>
            <th style="min-width:200px;">{{item.label}}</th>
            <td style="min-width:700px">
              <template>
                <template v-if="item.type==='upload'">
                  <template v-if="editForm[item.title]&&editForm[item.title].length>0">
                    <a v-for="(it,idx) in editForm[item.title]" :key="idx" :href="$http.defaults.baseURL + $http.defaults.unitReportAPI + 'api/file/download?id=' + it.id">{{it.name}}<br></a>
                  </template>
                  <template v-else>无</template>
                </template>
                <template v-else-if="item.type==='checkbox'">
                  {{editForm[item.title].join("、")}}
                </template>
                <template v-else>{{editForm[item.title]}}</template>
              </template>
            </td>
            <td style="min-width:300px">{{item.remarks}}
            </td>
          </template>
        </tr>
      </table>
      <table cellspacing="0" cellpadding="0" class="mytable" v-else>
        <tr v-for="(item,index) in formData" :key="index">
          <td style="min-width:700px">
            <el-form-item :prop="item.title" :label="item.label" :rules="item.rules">
              <el-input
                v-model="editForm[item.title]"
                v-if="item.type==='string'"
                style="width:400px;"
                :maxlength="item.config?item.config.maxlength:false"
                :minlength="item.config?item.config.minlength:false"
                :show-word-limit="true"
              ></el-input>
              <el-input
                v-model="editForm[item.title]"
                v-else-if="item.type==='textarea'"
                style="width:600px;"
                type="textarea"
                :rows="item.config?item.config.rows:5"
                :maxlength="item.config?item.config.maxlength:false"
                :minlength="item.config?item.config.minlength:false"
                :show-word-limit="true"
              >
              </el-input>
              <el-input-number
                v-model="editForm[item.title]"
                v-else-if="item.type==='number'"
                :precision="item.config?item.config.precision:0"
                :step="item.config?item.config.step:1"
                :min="item.config?item.config.min:null"
                :max="item.config?item.config.max:null"
              >
              </el-input-number>
              <el-date-picker
                v-model="editForm[item.title]"
                v-else-if="item.type==='date'"
                :type="item.dateType?item.dateType:'date'"
                :value-format="item.format?item.format:'yyyy-MM-dd'"
                placeholder="选择日期"
              >
              </el-date-picker>
              <el-radio-group
                v-model="editForm[item.title]"
                v-else-if="item.type==='radio'"
              >
                <el-radio v-for="(it,idx) in item.options" :key="idx" :label="it"></el-radio>
              </el-radio-group>
              <el-checkbox-group
                v-model="editForm[item.title]"
                v-else-if="item.type==='checkbox'"
              >
                <el-checkbox v-for="(it,idx) in item.options" :key="idx" :label="it"></el-checkbox>
              </el-checkbox-group>
              <el-select
                v-model="editForm[item.title]"
                v-else-if="item.type==='select'"
                placeholder="请选择"
              >
                <el-option
                  v-for="(it,idx) in item.options"
                  :key="idx"
                  :label="it"
                  :value="it">
                </el-option>
              </el-select>
              <el-upload
                v-model="editForm[item.title]"
                v-else-if="item.type==='upload'"
                :action="$http.defaults.baseURL+$http.defaults.unitReportAPI +'api/file/upload/'"
                :on-preview="handlePreview"
                :on-remove="(file, fileList)=>{return handleRemove(file, fileList, item.title)}"
                :on-success="(response, file, fileList)=>{return handleUploadSucc(response, file, fileList, item.title)}"
                :on-error="uploadError"
                :before-remove="beforeRemove"
                :before-upload="beforeUpload"
                :multiple="false"
                :on-exceed="handleExceed"
                :limit="item.config?item.config.limit:null"
                :file-list="editForm[item.title]">
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </td>
          <td style="min-width:300px">{{item.remarks}}
          </td>
        </tr>
      </table> -->
            <!-- {{JSON.stringify(editForm)}}
            {{JSON.stringify(formFiles)}} -->
      <template v-if="!readOnly">
        <el-button type="primary" @click.native="editFormSubmit()" :loading="saveloading" style="margin-left:20px;">提交</el-button>
      </template>
    </el-form>
  </div>
</template>

<script>
export default {
  watch: {
    timestamp: {
      handler (val) {
        this.getDetail(this.projectId)
      },
      immediate: true
    },
    filterText (val) {
      this.$refs.tree.filter(val)
    }
  },
  props: {
    timestamp: '',
    projectId: null,
    readOnly: false,
    item: {}
  },
  data () {
    return {
      limitNum: '',
      formData: [],
      pageLoading: false,
      saveloading: false,
      editForm: {
      },
      formFiles: {}
    }
  },
  methods: {
    checkLimit (item, arr) {
      // let label = item.options[index]
      // let limitNum = item.limitNum[index]
      // item.inputNum[index] = 1
      let para = {
        projectId: this.projectId,
        key: item.title,
        values: item.options
      }
      this.$http.post(this.$http.defaults.unitReportAPI + `api/project/queryCountByKeyValue`, para).then(response => {
        // debugger
        if (response.data.success === true) {
          this.$set(item, 'inputNum', response.data.result)
          let labelText = []
          for (let i = 0; i < item.inputNum.length; i++) {
            labelText.push(item.options[i] + '（限填' + item.limitNum[i] + '条，已填' + item.inputNum[i] + '条）')
          }
          this.$set(item, 'labelText', labelText)
          console.log(arr)
        }
      })
    },
    uploadError (err) {
      this.saveloading = false
      console.log(err)
      this.$message({
        message: '上传失败:' + err,
        type: 'error'
      })
    },
    beforeRemove (file, fileList) {
      if (file && file.status === 'success') {
        return this.$confirm(`确定删除 ${file.name}？`)
      }
    },
    handleUploadSucc (response, file, fileList, title) {
      console.log(fileList)
      this.saveloading = false
      if (response.success) {
        this.editForm[title] = fileList.map(item => {
          if (item.response) {
            return {name: item.response.result[0].fileName + '.' + item.response.result[0].fileType, id: item.response.result[0].id}
          } else {
            return item
          }
        }
        )
        // this.$nextTick(() => {
        //   this.editForm[title] = this.formFiles[title].map(item => item.id)
        // })
        this.$message({
          message: '上传成功！' + response.message,
          type: 'success'
        })
      } else {
        this.$message({
          message: '上传失败:' + response.message,
          type: 'error'
        })
      }
    },
    handlePreview (file) {
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(this.$http.defaults.baseURL + this.$http.defaults.unitReportAPI + 'api/file/download?id=' + file.id, file.name)
      } else {
        var link = document.createElement('a')
        link.download = file.name
        link.href = this.$http.defaults.baseURL + this.$http.defaults.unitReportAPI + 'api/file/download?id=' + file.id
        link.click()
        console.log(this.$http.defaults.unitReportAPI + 'api/file/download?id=' + file.id)
        window.URL.revokeObjectURL(link.href)
      }
    },
    handleRemove (file, fileList, title) {
      if (file && file.status === 'success') {
        console.log(file, fileList)
        const fid = file.id
        const url = 'api/file/remove'
        let para = {
          params: {
            id: fid
          }
        }
        this.$http.get(this.$http.defaults.unitReportAPI + url, para).then(res => {
          console.log('删除成功:', res)
          if (res.data.success === true) {
            this.editForm[title] = fileList.map(item => {
              if (item.response) {
                return {name: item.response.result[0].fileName + '.' + item.response.result[0].fileType, id: item.response.result[0].id}
              } else {
                return item
              }
            })
            // this.$nextTick(() => {
            //   this.editForm[title] = this.formFiles[title].map(item => item.id)
            // })
            this.$message({
              message: '删除成功！',
              type: 'success'
            })
          }
        })
      }
    },
    beforeUpload (file) {
      // const isFormat = file.name.indexOf('.zip') > 0
      const isLt50M = file.size / 1024 / 1024 < 5000
      if (!isLt50M) {
        this.$message.error('单个附件不能超过50M!')
      } else {
        this.saveloading = true
      }
      return isLt50M
    },
    handleExceed (files, fileList) {
      this.$message.warning(`上传文件个数超限`)
    },
    editFormSubmit () {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          if (this.readOnly) {
            this.$message({
              message: '测试提交成功！',
              type: 'success'
            })
          } else {
            // 返回父页面数据
            this.$emit('addData', JSON.parse(JSON.stringify(this.editForm)))
            // this.editForm = {}
          }
        }
      })
    },
    getDetail (id) {
      if (id) {
        this.pageLoading = true
        this.$http
          .get(this.$http.defaults.unitReportAPI + `api/project/getProjectById?id=` + id)
          .then(response => {
            if (response.data.result.reportTemplate) {
              this.formData = JSON.parse(response.data.result.reportTemplate).columns
              this.limitNum = JSON.parse(response.data.result.reportTemplate).limitNum
              this.editForm = {}
              this.formData.forEach((element) => {
                if (element.children) {
                  element.children.forEach((childElement) => {
                    if ((childElement.type === 'radio' || childElement.type === 'select') && childElement.limitNum) {
                      if (!this.readOnly) {
                        this.checkLimit(childElement)
                      }
                    } else {
                      if (childElement.defaultValue) {
                        this.$set(this.editForm, childElement.title, childElement.defaultValue)
                      } else {
                        if (childElement.type === 'checkbox' || childElement.type === 'upload') {
                          this.$set(this.editForm, childElement.title, [])
                        } else {
                          this.$set(this.editForm, childElement.title, null)
                        }
                        if (childElement.type === 'upload') {
                          this.$set(this.formFiles, childElement.title, [])
                        }
                      }
                    }
                  })
                } else {
                  if ((element.type === 'radio' || element.type === 'select') && element.limitNum) {
                    if (!this.readOnly) {
                      this.checkLimit(element)
                    }
                  } else {
                    // 如果单选有限制每个选项的限制数量，默认值设置不生效，避免默认值超出时填写冲突
                    if (element.defaultValue) {
                      this.$set(this.editForm, element.title, element.defaultValue)
                    } else {
                      console.log('没有默认值')
                      console.log(element.title)
                      if (element.type === 'checkbox' || element.type === 'upload') {
                        this.$set(this.editForm, element.title, [])
                      } else {
                        console.log(element.title)
                        this.$set(this.editForm, element.title, null)
                      }
                      if (element.type === 'upload') {
                        this.$set(this.formFiles, element.title, [])
                      }
                    }
                  }
                }
              })

              if (this.item && JSON.stringify(this.item) !== '{}') {
                console.log('修改')
                this.editForm = JSON.parse(this.item.dataJson)
                this.editForm.id = this.item.id
              }
            }
            this.pageLoading = false
          })
          .catch(error => {
            this.$message({
              message: '网络获取失败:' + error,
              type: 'error'
            })
          })
      }
    }
  },
  mounted () {
  }
}
</script>
<style>
#assessdetail .el-upload-list__item{
  width: 250px;
}
#assessdetail a{
  width: 200px;
}
.assessdetail .el-tabs__header{
  height: 29px;
  background: #FAFAFA;
  line-height: 30px;
  font-family: '宋体';
  padding:0 20px;
  border-bottom: 2px solid #E4E7ED;
  margin:0;
}
.assessdetail .el-tabs__item{
  line-height: 30px;
  height: 30px;
  font-weight:bolder;
}
  .cardtab .el-tabs__header{
    padding:0 !important;
    border-bottom:1px solid #E4E7ED;
  }
  #assessdetail .wboxs{
    height:45px;
    padding-top:0;
    margin-bottom: 10px;
  }
  .wboxs{
    padding:5px 15px;
    width: calc(100% - 30px);
    background: #fff;
    border: 1px solid #95B8E7;
    margin:0 10px;
    overflow: hidden;
  }
</style>

<style scoped>
  .tickettable th{
    font-weight:lighter;
    background-image: linear-gradient(to bottom , #f8f8f8, #efefef);
    text-align: center;
  }
  .tickettable{
    width: 100%;
    border-left: 1px solid #95B8E7;
    border-top: 1px solid #95B8E7;
  }
  .tickettable td, .tickettable th{
    padding:5px 10px;
    margin:0;
    font-size:var(--size14) !important;
    line-height: 20px;
    font-family: '宋体';
    border-bottom: 1px solid #95B8E7;
    border-right: 1px solid #95B8E7;
  }
  .tickettable td{
    vertical-align: middle;
    text-align: center;
    font-weight: bolder;
  }
  .mytable{
    border-top: 1px solid #74a6cc;
    border-left: 1px solid #74a6cc;
    margin:0 10px 10px;
    width: calc(100% - 20px);
  }
  .mytable th{
    padding: 10px;
    border-right: 1px solid #74a6cc;
    border-bottom: 1px solid #74a6cc;
    line-height: 150%;
    background: #FAFAFA;
    width:200px;
    text-align:right;
  }
  .mytable td{
    padding: 10px;
    border-right: 1px solid #74a6cc;
    border-bottom: 1px solid #74a6cc;
    vertical-align: top;
    line-height: 150%;
  }
</style>
